package ga.cross;

public class Cross {

	/*
	 * Transforma un array de bytes en un array de bits
	 */
	public static boolean[] bytesToBits (byte[] bytes) {
		boolean[] bitsArray = new boolean[8*bytes.length];
		int index = 0;
		for (byte b: bytes) {
			boolean[] bits = byteToBits(b);
			for (int i = 0; i < 8; i++) {
				bitsArray[index] = bits[i];
				index++;
			}
		}
		return bitsArray;
	}
	
	/*
	 * Transforma un byte en un vector de bits
	 */
	private static boolean[] byteToBits (byte b) {
		boolean[] bitsArray = new boolean[8];
		byte mask = 0x01; 
		for (int i = 7; i >= 0; i--) {
			bitsArray[i] = ((b & mask) != 0);
			b >>= 1;
		}
		return bitsArray;
	}

	public static byte[] bitsToBytes(boolean[] bitArrayFirstIndividual) throws IllegalArgumentException {
		if (bitArrayFirstIndividual.length % 8 != 0) {
			throw new IllegalArgumentException("Invalid bit Array!");
		}
		byte[] byteArray = new byte[bitArrayFirstIndividual.length / 8];
		int index = 0;
		for (int i = 0; i < bitArrayFirstIndividual.length / 8; i++) {
			byteArray[i] = bitsToByte(subArray(bitArrayFirstIndividual, index, index+8));
			index += 8;
		}
		return byteArray;
	}
	
	private static boolean[] subArray(boolean[] bitArrayFirstIndividual, int lower, int higher) {
		boolean[] newArray = new boolean[higher-lower];
		int j = 0;
		for (int i = lower; i < higher; i++) {
			newArray[j] = bitArrayFirstIndividual[i];
			j++;
		}
		return newArray;
	}

	private static byte bitsToByte (boolean[] bits) {
		byte b = 0x00;
		for (int i = 0; i < 8; i++) {
			if (bits[i]) {
				b += 0x01;
			}
			b <<= 1;
		}
		return b;
	}
}
